﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ServiceCore;

namespace Api.Filter
{
    public class RK_Admin : Attribute, IActionFilter
    {
        /// <summary>
        /// action执行之后的拦截控制器
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //Console.WriteLine("action执行之后");
        }
        /// <summary>
        /// action执行之前的拦截控制器
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.HttpContext.Request.Method.ToLower() == "options")
            {
                context.Result = new ContentResult() { StatusCode = 204, Content = "..." };
            }
            //Console.WriteLine("action执行之前");
            if (!FilterJWT(context))
            {
                //不符合JWT规则
                context.Result = new ContentResult() { ContentType = "application/json", StatusCode = 200, Content = Newtonsoft.Json.JsonConvert.SerializeObject(new { code = "888", msg = "AUTH_ERROR " }) };
            }
        }

        /// <summary>
        /// 验证JWT
        /// </summary>
        /// <returns></returns>
        private bool FilterJWT(ActionExecutingContext context)
        {
            string token = "";

            if (context.HttpContext.Request.Headers["token"].FirstOrDefault() != null)
            {
                token = context.HttpContext.Request.Headers["token"].FirstOrDefault();
            }
            else if (context.HttpContext.Request.Query["token"].FirstOrDefault() != null)
            {
                token = context.HttpContext.Request.Query["token"].FirstOrDefault();
            }
            if (string.IsNullOrWhiteSpace(token))
            {
                return false;
            }
            if (!JWT.Jwt.Check(token))
            {
                return false;
            }
            try
            {
                TokenUser tokenUser = Newtonsoft.Json.JsonConvert.DeserializeObject<TokenUser>(Newtonsoft.Json.JsonConvert.SerializeObject(JWT.Jwt.GetPayLoad(token)));
                if (tokenUser != null)
                {
                    return true;
                }
                return false;
            }
            catch(Exception ex)
            {
                return false;
            }
        }
    }
}
